package com.qymerge.manage.base.dao.impl;

import com.qymerge.manage.base.dao.ICardDao;
import com.qymerge.manage.base.dao.IOrganizationalStructureDao;
import com.qymerge.manage.base.ro.OrganizationalStructureRO;
import com.qymerge.manage.core.bean.PageRequest;
import com.qymerge.manage.core.constant.ParamKey;
import com.qymerge.manage.core.dao.BaseDao;
import com.qymerge.manage.system.ro.SysMenuRO;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 *
 * @author Xiao
 * @date 2025/4/25 16:38
 * @version 1.0.0
 */
@Repository
public class OrganizationalStructureDaoImpl extends BaseDao implements IOrganizationalStructureDao {

    private String dwd_MCRS_MDM_organizational_structure = "SELECT id,Company, Depart, NoeLevel, Center, parent_id, create_user_id,create_user_name, create_time, sort, status FROM dwd_MCRS_MDM_organizational_structure WHERE 1=1 ";

    @Override
    public List list(OrganizationalStructureRO ro, PageRequest pageRequest) {
        int skip = (pageRequest.getPage() - 1) * pageRequest.getSize();
        int size = pageRequest.getSize();

        String sql = dwd_MCRS_MDM_organizational_structure;
        Map<String, Object> paramMap = new HashMap<String, Object>();

        if (ro.getId() > 0) {
            sql += " and id=:id";
            paramMap.put("id", ro.getId());
        }

        if (StringUtils.isNotBlank(ro.getCompany())) {
            sql += " and Company like :Company";
            paramMap.put("Company", "%" + ro.getCompany() + "%");
        }

        // 分页数据获取
        sql += " order by sort desc limit :skip,:sizes";
        paramMap.put("skip", skip);
        paramMap.put("sizes", size);

        return getNamedParameterJdbcTemplate().query(sql, paramMap, new BeanPropertyRowMapper<OrganizationalStructureRO>(OrganizationalStructureRO.class));
    }

    @Override
    public int total(OrganizationalStructureRO ro) {
        String sql = "select count(1) from dwd_MCRS_MDM_organizational_structure where 1=1";
        Map<String, Object> paramMap = new HashMap<String, Object>();

        if (ro.getId() > 0) {
            sql += " and id=:id";
            paramMap.put("id", ro.getId());
        }


        if (StringUtils.isNotBlank(ro.getCompany())) {
            sql += " and Company like :Company";
            paramMap.put("Company", "%" + ro.getCompany() + "%");
        }

        return getNamedParameterJdbcTemplate().queryForObject(sql, paramMap, Integer.class);
    }

    @Override
    public OrganizationalStructureRO findOne(Long id) {
        StringBuffer sql = new StringBuffer(dwd_MCRS_MDM_organizational_structure);
        sql.append("and id=?");
        RowMapper<OrganizationalStructureRO> rowMapper = new BeanPropertyRowMapper<OrganizationalStructureRO>(OrganizationalStructureRO.class);
        try {
            return getJdbcTemplate().queryForObject(sql.toString(), rowMapper, id);
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public List<OrganizationalStructureRO> findAll() {
        StringBuffer sql = new StringBuffer(dwd_MCRS_MDM_organizational_structure);
        RowMapper<OrganizationalStructureRO> rowMapper = new BeanPropertyRowMapper<OrganizationalStructureRO>(OrganizationalStructureRO.class);
        return getJdbcTemplate().query(sql.toString(), rowMapper);
    }

    @Override
    public List<OrganizationalStructureRO> findAll(OrganizationalStructureRO ro) {
        StringBuffer sql = new StringBuffer(dwd_MCRS_MDM_organizational_structure);
        Map<String, Object> paramMap = new HashMap<String, Object>();

        if (ro.getOrgVersionId() > 0) {
            sql.append(" and orgVersionId=:orgVersionId");
            paramMap.put("orgVersionId", ro.getOrgVersionId());
        }

        sql.append(" order by sort desc");
        return getNamedParameterJdbcTemplate().query(sql.toString(), paramMap, new BeanPropertyRowMapper<OrganizationalStructureRO>(OrganizationalStructureRO.class));
    }

    @Override
    public int install(OrganizationalStructureRO ro) {
        StringBuilder sql = new StringBuilder("insert into dwd_MCRS_MDM_organizational_structure(Company, Depart, Center, NoeLevel, parent_id, sort, orgVersionId, create_user_id, create_user_name, create_time, status) values(?,?,?,?,?,?,?,?,?,?,?)");

        List params = new ArrayList();
        params.add(ro.getCompany());
        params.add(ro.getDepart());
        params.add(ro.getCenter());
        params.add(ro.getNoeLevel());
        params.add(ro.getParent_id());
        params.add(ro.getSort());

        params.add(ro.getOrgVersionId());

        params.add(ro.getCreate_user_id());
        params.add(ro.getCreate_user_name());
        params.add(ro.getCreate_time());
        params.add(ro.getStatus());

        return getJdbcTemplate().update(sql.toString(), params.toArray());
    }

    @Override
    public int update(OrganizationalStructureRO ro) {
        StringBuilder sql = new StringBuilder("update dwd_MCRS_MDM_organizational_structure set Company=:Company, Depart=:Depart, Center=:Center, NoeLevel=:NoeLevel, sort=:sort, update_user_id=:update_user_id, update_user_name=:update_user_name, update_time=:update_time, status=:status where id=:id ");

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("Company", ro.getCompany());
        paramsMap.put("Depart", ro.getDepart());
        paramsMap.put("Center", ro.getCenter());
        paramsMap.put("NoeLevel", ro.getNoeLevel());
        paramsMap.put("sort", ro.getSort());
        paramsMap.put("update_user_id", ro.getUpdate_user_id());
        paramsMap.put("update_user_name", ro.getUpdate_user_name());
        paramsMap.put("update_time", ro.getUpdate_time());
        paramsMap.put("status", ro.getStatus());

        paramsMap.put("id", ro.getId());
        return getNamedParameterJdbcTemplate().update(sql.toString(), paramsMap);
    }

    @Override
    public int remove(List<Long> ids) {
        // 删除
        String sql="delete from dwd_MCRS_MDM_organizational_structure where id=?";
        final List<Long> idss = ids;
        BatchPreparedStatementSetter setterMid = new BatchPreparedStatementSetter(){

            @Override
            public int getBatchSize(){
                return idss.size();
            }

            @Override
            public void setValues(PreparedStatement ps, int i){
                Long id = idss.get(i);
                try {
                    ps.setLong(1, id);
                } catch(Exception e){
                    logger.error("batchInsertWaitAward Exception:", e);
                }
            }
        };
        return getJdbcTemplate().batchUpdate(sql, setterMid).length;
    }

    @Override
    public int remove(Long id) {
        // 删除
        String sql="delete from dwd_MCRS_MDM_organizational_structure where id=?";
        return getJdbcTemplate().update(sql, id);
    }

    @Override
    public boolean ifExists(Long id) {
        StringBuffer sql = new StringBuffer("select count(1) from dwd_MCRS_MDM_organizational_structure where id=?");
        try {
            return getJdbcTemplate().queryForObject(sql.toString(), Integer.class, id) > 0;
        } catch (DataAccessException e) {
            return false;
        }
    }

    @Override
    public List<OrganizationalStructureRO> findAllByParentId(Long id) {
        NamedParameterJdbcTemplate jdbc = new NamedParameterJdbcTemplate(this.getJdbcTemplate());
        String sql = "select * from dwd_MCRS_MDM_organizational_structure where parent_id in(:param)";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("param", id);
        return jdbc.query(sql, paramMap, new BeanPropertyRowMapper<OrganizationalStructureRO>(OrganizationalStructureRO.class));
    }


}
